import java.util.Random;

public class BlockingQueue {
    private volatile int size = 0;
    private int[] arr = new int[100];
    private int head=0, tail=0;
    public void put(int num) throws InterruptedException {
        // 先做判断，如果满了那么停止放入，并给消费那边发信号赶紧回收；如果一开始就是空的（无论是不是空的）都给生产者发个信号提示一下
        synchronized (this){
            while(this.size==arr.length) {
                wait();
            }
            arr[tail++]=num;
            tail= (tail)%arr.length;
            // addSize();     这里犯了加了两重锁的错误
            size++;
            notifyAll();
        }
    }

    private synchronized void addSize(){
        this.size++;
    }
    private synchronized void desSize(){this.size--;}

    public int take() throws InterruptedException{
        int res = 0;
        synchronized (this){

            while(this.size==0){
                wait();
            }

            res = arr[head];
            head++;
            head = head%arr.length;
            size--;
            notifyAll();
        }
        return res;
    }


    public synchronized int getSize(){
        return this.size;
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new BlockingQueue();
        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int value = blockingQueue.take();
                    System.out.println("消费者消费了："+value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者");
        customer.start();
        Thread producer = new Thread(() -> {
            Random random = new Random();
            while (true) {
                try {
                    int num = random.nextInt(10000);
                    blockingQueue.put(num);
                    System.out.println("生产者生产了："+ num);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "生产者");
        producer.start();
        customer.join();
        producer.join();
    }

}
